package com.td.spring.beans.context;

import com.td.spring.beans.BeanPostProcessor;
import com.td.spring.beans.factory.AbstractBeanFactory;
import com.td.spring.beans.factory.BeanFactory;

import java.util.List;

/**
 * @author td
 * @date 2018/6/5
 */
public abstract class AbstractApplicationContext implements ApplicationContext {

    protected AbstractBeanFactory beanFactory;

    public AbstractApplicationContext(AbstractBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }
    // 加载beanDefinition
    protected abstract void loadBeanDefinitions(AbstractBeanFactory beanFactory) throws Exception;

    // 注册beanPost
    protected  void registerBeanPostProcessors(AbstractBeanFactory beanFactory) throws Exception {
        List beanPostProcessors = beanFactory.getBeansForType(BeanPostProcessor.class);
        for (Object beanPostProcessor : beanPostProcessors) {
            beanFactory.addBeanPostProcessor((BeanPostProcessor) beanPostProcessor);
        }
    }

    // 刷新
    protected  void onRefresh() throws Exception {
        beanFactory.preInstantiateSingletons();
    }

    public void refresh() throws Exception {
        loadBeanDefinitions(this.beanFactory);
        registerBeanPostProcessors(this.beanFactory);
        onRefresh();

    }

    @Override
    public Object getBean(String name) throws Exception {
        return beanFactory.getBean(name);
    }
}
